import React, { useEffect } from "react";
import { Button } from 'antd'
import BpmnModeler from 'bpmn-js/lib/Modeler'
import { xml as xmlstr } from '../../bpmn/create/xml'
import 'bpmn-js-properties-panel/dist/assets/properties-panel.css' // 右边工具栏样式

// 左边工具栏以及编辑节点的样式
import 'bpmn-js/dist/assets/diagram-js.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css'
import customTranslate from './customTranslate/customTranslate'

import './index.less'

// 右侧属性栏
import {
  BpmnPropertiesPanelModule,
  BpmnPropertiesProviderModule,
  CamundaPlatformPropertiesProviderModule
} from 'bpmn-js-properties-panel';

import CamundaExtensionModule from 'camunda-bpmn-moddle/lib'

// 一个描述的json
import camundaModdleDescriptors from 'camunda-bpmn-moddle/resources/camunda';
var customTranslateModule = {
  translate: ['value', customTranslate]
};

const bpmnModeler = new BpmnModeler({
  //添加控制板
  propertiesPanel: {
    parent: '#js-properties-panel'
  },

})
function App() {
  let bpmnModeler = null;

  useEffect(() => {
    bpmnModeler = null
    initBpmn()
  }, [])

  const initBpmn = () => {
    bpmnModeler = new BpmnModeler({
      container: '#container',
      height: '100vh',
      propertiesPanel: {
        parent: '#properties-panel'
      },
      additionalModules: [
        BpmnPropertiesPanelModule,
        BpmnPropertiesProviderModule,
        CamundaPlatformPropertiesProviderModule,
        CamundaExtensionModule,
        customTranslateModule
      ],
      moddleExtensions: {
        //如果要在属性面板中维护camunda：XXX属性，则需要此 
        camunda: camundaModdleDescriptors
      }
    })
    createBpmnDiagram()
  }
  const createBpmnDiagram = async () => {
    try {
      const result = await bpmnModeler.importXML(xmlstr)
    } catch (e) {
      console.log(e);

    }
  }

  const getFilename = (xml) => {
    let start = xml.indexOf("process");
    let filename = xml.substr(start, xml.indexOf(">"));
    filename = filename.substr(filename.indexOf("id") + 4);
    filename = filename.substr(0, filename.indexOf('"'));
    return filename;
  }

  const saveBpmn = (withActiviti = false) => {
    console.log("saveBpmn");

    bpmnModeler.saveXML({ format: true }, (err, xml) => {
      if (!err) {
        if (withActiviti) {
          xml = xml.replace(/camunda/ig, "activiti");
        }
        // 获取文件名
        const name = `${getFilename(xml)}.bpmn`;
        // 将文件名以及数据交给下载方法
        const encodedData = encodeURIComponent(xml);
        if (xml) {
          const link = document.createElement('a')
          // 将数据给到链接
          link.href = "data:application/bpmn20-xml;charset=UTF-8," + encodedData;
          // 设置文件名
          link.download = name;
          // 触发点击事件开始下载
          link.click();
        }
      }
    });
  }


  const saveSvg = () => {
    console.log("saveSvg");
    bpmnModeler.saveXML({ format: true }, (err, xml) => {
      if (!err) {
        // 获取文件名
        const name = `${getFilename(xml)}.svg`;

        if (xml) {
          // 从建模器画布中提取svg图形标签
          let context = "";
          const djsGroupAll = document.querySelectorAll(".djs-group");
          for (let item of djsGroupAll) {
            context += item.innerHTML;
          }
          // 获取svg的基本数据，长宽高
          const viewport = document.querySelector(".viewport")?.getBBox();

          // 将标签和数据拼接成一个完整正常的svg图形
          const svg = `
              <svg
                xmlns="http://www.w3.org/2000/svg"
                xmlns:xlink="http://www.w3.org/1999/xlink"
                width="${viewport.width}"
                height="${viewport.height}"
                viewBox="${viewport.x} ${viewport.y} ${viewport.width} ${viewport.height}"
                version="1.1"
                >
                ${context}
              </svg>
            `;
          const link = document.createElement('a')
          // 将数据给到链接
          // 将文件名以及数据交给下载方法
          const encodedData = encodeURIComponent(svg);
          link.href = "data:application/bpmn20-xml;charset=UTF-8," + encodedData;
          // 设置文件名
          link.download = name;
          // 触发点击事件开始下载
          link.click();
        }
      }
    });
  }

  return (
    <div className="content with-diagram">

      <ul className="buttons">
        <li>
          下载
        </li>
        <li>
          <Button type="primary" onClick={() => saveBpmn()}>BPMN FOR CAMUNDA</Button>
        </li>
        <li>
          <Button type="primary" onClick={() => saveBpmn(true)}>BPMN FOR ACTIVITI</Button>
        </li>
        <li>
          <Button type="primary" onClick={() => saveSvg()}>SVG</Button>
        </li>
      </ul>
      <div
        id="container"
        className="canvas"
      ></div>
      <div
        id="properties-panel"
        className="properties-panel-parent"
      ></div>
    </div>
  );
}
export default App;
